﻿using Microsoft.Extensions.Options;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;

namespace BaBaoFan.Modifier.Data
{
    public class PmDbConnection
    {
        private IDbConnection _dbConnection;
        public Guid ConnectionId { get; private set; }

        public PmDbConnection(IOptions<DbSettings> dbSettings)
        {
            ConnectionId = Guid.NewGuid();
            _dbConnection = new MySqlConnection(dbSettings.Value.PmConnectionString);
        }

        public IDbConnection Connection
        {
            get
            {
                //design: only open when needed.
                if (_dbConnection.State == ConnectionState.Closed)
                {
                    _dbConnection.Open();
                }
                return _dbConnection;
            }
        }

        public void Dispose()
        {
            if (_dbConnection != null && _dbConnection.State == ConnectionState.Open)
            {
                _dbConnection.Close();
                _dbConnection.Dispose();
            }
        }
    }
}
